﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Attributes;
using Entity.Car_Rental;
using Standard;
using Entity.CommonEnums;
using System.Configuration;
using VCommons.Encryptor;
using Web.Commons;
using tenpay;
using OnlinePayment;
using Data.Car_Rental;
using System.Collections.Specialized;
using System.Text;
namespace Car_Rental.Controllers
{
    public class OrderController : BaseController
    {

        #region 回写地址
        /// <summary>
        /// 支付宝回写地址
        /// </summary>
        protected string AlipayReturnAddress { get { return DoMain + "/Order/AlipayReturn"; } }
        /// <summary>
        /// 支付宝回写地址(服务器回写)
        /// </summary>
        protected string AlipayNotifyAddress { get { return DoMain + "/Order/AlipayNotify"; } }
        /// <summary>
        /// 财富通回写地址
        /// </summary>
        protected string TenpayReturnAddress { get { return DoMain + "/Order/TenpayReturn"; } }
        /// <summary>
        /// 银联回写地址
        /// </summary>
        protected string ChinaPayRetUrlAddress { get { return DoMain + "/Order/ChinaPayRetUrl"; } }
        #endregion
        int orderID;
        IOrderRespository iOrderRespository = null;
        IRentalRecordRepository iRentalRecordRepository = null;
        public OrderController()
        {

            iOrderRespository = new OrderRespository();
            iRentalRecordRepository = new RentalRecordRepository();
        }
        #region 服务器返回，与业务有关
        public void AlipayReturn()
        {
            if (Request.Params["Priv1"] != null)
            {
                orderID = Convert.ToInt32(Utility.DecryptString(Request.Params["Priv1"].ToString()).Split('|')[1].Split(',')[1]);
            }
            OnlineReturn onlineReturn = new OnlineReturn();
            onlineReturn.OnlineSuccess += delegate
            {
                //订单支付成功后的逻辑，可能是改订单状态 
                iOrderRespository.FinishOrder(new Order { OrderID = orderID, Status = (int)OrderStatus.Finish });
            };

            onlineReturn.AlipayReturn();

        }
        public void AlipayNotify()
        {
            if (Request.Params["Priv1"] != null)
            {
                orderID = Convert.ToInt32(Utility.DecryptString(Request.Params["Priv1"].ToString()).Split('|')[1].Split(',')[1]);
            }
            OnlineReturn onlineReturn = new OnlineReturn();
            onlineReturn.OnlineSuccess += delegate
            {
                //订单支付成功后的逻辑，可能是改订单状态 
                iOrderRespository.FinishOrder(new Order { OrderID = orderID, Status = (int)OrderStatus.Finish });
            };
            onlineReturn.AlipayNotify();

        }

        public void TenpayReturn()
        {
            if (Request.Params["Priv1"] != null)
            {
                orderID = Convert.ToInt32(Utility.DecryptString(Request.Params["Priv1"].ToString()).Split('|')[1].Split(',')[1]);
            }
            OnlineReturn onlineReturn = new OnlineReturn();
            onlineReturn.OnlineSuccess += delegate
            {
                //订单支付成功后的逻辑，可能是改订单状态 
                iOrderRespository.FinishOrder(new Order { OrderID = orderID, Status = (int)OrderStatus.Finish });
            };
            onlineReturn.TenpayReturn();

        }

        public void ChinaPayRetUrl()
        {
            if (Request.Params["Priv1"] != null)
            {
                orderID = Convert.ToInt32(Utility.DecryptString(Request.Params["Priv1"].ToString()).Split('|')[1].Split(',')[1]);
            }
            OnlineReturn onlineReturn = new OnlineReturn();
            onlineReturn.OnlineSuccess += delegate
            {
                //订单支付成功后的逻辑，可能是改订单状态 
                iOrderRespository.FinishOrder(new Order { OrderID = orderID, Status = (int)OrderStatus.Finish });
            };
            onlineReturn.ChinaPayRetUrl();

        }
        #endregion


        //
        // GET: /Order/
        [UserAuthentication(AuthenticationType.Login)]
        public ActionResult Index()
        {
            Standard.RentalCar rentalCar = Standard.ClientHelper.Current.RentalCar.GetRentalCarImplement();
            if (rentalCar == null || rentalCar.StartTime == DateTime.MinValue)
                return RedirectToAction("Index", "Car", new
                {
                    ProductID = Request.QueryString["ProductID"],
                    ProductPropertyID = Request.QueryString["ProductID"],
                    Price = Request.QueryString["Price"]
                });
            Entity.Car_Rental.RentalRecord entity = new Entity.Car_Rental.RentalRecord();
            entity.ProductID = string.IsNullOrEmpty(Request.QueryString["ProductID"]) ? rentalCar.ProductID : Convert.ToInt32(Request.QueryString["ProductID"]);
            entity.Price = string.IsNullOrEmpty(Request.QueryString["Price"]) ? rentalCar.Price : Convert.ToDecimal(Request.QueryString["Price"]);
            entity.StartTime = rentalCar.StartTime;
            entity.EndTime = rentalCar.EndTime;
            entity.ReturnCity = rentalCar.ReturnCity;
            entity.ReturnShop = rentalCar.ReturnShop;
            Product product = new ProductRepository().GetModelForSite().FirstOrDefault(i => i.ProductID == entity.ProductID);
            entity.Product_Extend = product;
            rentalCar.ProductID = entity.ProductID;
            rentalCar.Price = entity.Price;
            Standard.ClientHelper.AddRentalCar(rentalCar);
            return View(entity);
        }
        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            Standard.RentalCar rentalCar = Standard.ClientHelper.Current.RentalCar.GetRentalCarImplement();
            Product product = new ProductRepository().GetModelForSite().FirstOrDefault(i => i.ProductID == Convert.ToInt64(form["ProductID"]));
            Order order = new Order
             {
                 BuyerUserID = base.Current_UserID,
                 CreateDate = DateTime.Now,
                 InvoiceAmount = 0,
                 InvoiceBody = string.Empty,
                 InvoiceTitle = string.Empty,
                 Note = form["Note"],
                 IsDelivery = false,
                 IsInvoice = false,
                 OrderAmount = Convert.ToDecimal(form["Price"]),
                 OrderStatus = (int)OrderStatus.PendingPayment,
                 PayType = Convert.ToInt32(form["PayType"]),
                 ProductSaleAmount = Convert.ToDecimal(form["Price"]),
                 RankCommentStatus = 0,
                 ShippingAmount = 0m,
                 ShippingMethods = string.Empty,
                 Status = (int)Status.Normal,
                 TaxAmount = 0m,
                 UpdateDate = DateTime.Now,
                 OrderItem_Extend = new List<OrderItem> 
                 { 
                    new  OrderItem
                     {
                        OrderItemID=Guid.NewGuid().ToString(),
                        ProductID=rentalCar.ProductID,
                        ProductName=product.ProductName,
                        Quantity=1,
                        SalePrice=rentalCar.Price,
                        Status=(int)Status.Normal,
                        RentalRecord_Extend=new RentalRecord {
                                                                CreateDate = DateTime.Now,
                                                                EndTime = rentalCar.EndTime,
                                                                Price = rentalCar.Price,
                                                                ProductID = rentalCar.ProductID,
                                                                ReturnCity = rentalCar.ReturnCity,
                                                                ReturnShop = rentalCar.ReturnShop,
                                                                StartTime = rentalCar.StartTime,
                                                                Status =form["isquene"]=="1"?(int)RentalRecordStatus.Queuing:(int)RentalRecordStatus.Scheduled,
                                                                UpateDate = DateTime.Now,
                                                                UserID = rentalCar.UserID,
                                                              }
                }
                 }
             };
            Order entity = iOrderRespository.GenerateOrder(order).Entity as Order;

            if (form["PayType"] == Convert.ToString((int)PayType.Online))
            {

                return RedirectToAction("OnlineTo", new { orderid = entity.OrderID, bankType = form["BankType"], money = entity.OrderAmount });

            }
            else
                return RedirectToAction("Success");

        }

        #region 在线支付发送
        /// <summary>
        /// 向第三方支付，发送请求
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="bankType"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public ActionResult OnlineTo(string orderid, string bankType, decimal money)
        {
            string exchangeID = string.Empty;
            int _bankType;
            string returnUrl = AlipayReturnAddress;
            string notifyUrl = AlipayNotifyAddress;
            if (!int.TryParse(bankType, out _bankType))
                _bankType = 1;
            switch (_bankType)
            {
                case 1:
                    returnUrl = AlipayReturnAddress;
                    notifyUrl = AlipayNotifyAddress;
                    break;
                case 2:
                    returnUrl = TenpayReturnAddress;
                    notifyUrl = TenpayReturnAddress;
                    break;
                case 4:
                    returnUrl = ChinaPayRetUrlAddress;
                    notifyUrl = ChinaPayRetUrlAddress;
                    break;
            }
            orderid = Utility.EncryptString((base.Current_UserID + "|" + orderid + "|2"), Utility.EncryptorType.DES);
            return Redirect(new PayParam().GetPayParam(_bankType, 2, orderid, money, base.Current_UserID, ref exchangeID, returnUrl, notifyUrl));
        }
        #endregion

        /// <summary>
        /// 购买成功页面
        /// </summary>
        /// <returns></returns> 
        public ActionResult Success()
        {
            return View();
        }

        /// <summary>
        /// 购买失败页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Fail()
        {
            return View();
        }

    }
}
